package org.jeecg.modules.demo.hdspecialsupervision.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.modules.demo.hdspecialsupervision.entity.HdSpecialSupervision;
import org.jeecg.modules.demo.hdspecialsupervision.mapper.HdSpecialSupervisionMapper;
import org.jeecg.modules.demo.hdspecialsupervision.service.IHdSpecialSupervisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.TimeZone;

/**
 * @Description: 专项监督
 * @Author: jeecg-boot
 * @Date:   2025-07-01
 * @Version: V1.0
 */
@Service
public class HdSpecialSupervisionServiceImpl extends ServiceImpl<HdSpecialSupervisionMapper, HdSpecialSupervision> implements IHdSpecialSupervisionService {

    @Autowired
    protected HdSpecialSupervisionMapper baseMapper;
    @Override
    public byte[] generateExcelBytes(List<HdSpecialSupervision> exportList) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("导出记录");

            // 设置默认行高和列宽
            sheet.setDefaultRowHeightInPoints(20); // 设置默认行高
            sheet.setDefaultColumnWidth(15); // 设置默认列宽

            // 创建样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle dataStyle = createDataStyle(workbook);

            Row titleRow = sheet.createRow(0);
            titleRow.setHeightInPoints(45); // 标题行高
            CellRangeAddress titleMerge = new CellRangeAddress(0, 0, 0, 8); // 合并0-8列（共9列）
            sheet.addMergedRegion(titleMerge);
            Cell titleCell = titleRow.createCell(0);
            // 修改标题生成逻辑，读取重点领域第一行数据并拼接
            String focusArea = exportList.isEmpty() ? "" : exportList.get(0).getFocusAreas();
            titleCell.setCellValue(focusArea + "领域专项监督台账");
            // 标题样式
            CellStyle titleStyle = workbook.createCellStyle();
            Font titleFont = workbook.createFont();
            titleFont.setBold(true);
            titleFont.setFontHeightInPoints((short) 16); // 字体大小
            titleStyle.setFont(titleFont);
            titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            titleCell.setCellStyle(titleStyle);

            // 3.2 第二行：部门名称+填报时间（左右分栏）
            Row infoRow = sheet.createRow(1);
            infoRow.setHeightInPoints(25); // 信息行高
            // 左边：部门名称（合并0-2列，左对齐）
            CellRangeAddress deptMerge = new CellRangeAddress(1, 1, 0, 2);
            sheet.addMergedRegion(deptMerge);
            Cell deptCell = infoRow.createCell(0);
            //修改成部门名称+excel得出的部门信息
            String companyDepartment = exportList.isEmpty() ? "" : exportList.get(0).getCompanyDepartment();
            deptCell.setCellValue("部门名称："+companyDepartment);
            CellStyle deptStyle = workbook.createCellStyle();
            deptStyle.setAlignment(HorizontalAlignment.LEFT);
            deptStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            deptCell.setCellStyle(deptStyle);
            // 右边：填报时间（合并3-4列，右对齐，动态获取当前年月）
            CellRangeAddress dateMerge = new CellRangeAddress(1, 1, 7, 8);
            sheet.addMergedRegion(dateMerge);
            Cell dateCell = infoRow.createCell(7);
            String reportDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")); // 格式：2025-07
            dateCell.setCellValue("导出时间：" + reportDate);
            CellStyle dateStyle = workbook.createCellStyle();
            dateStyle.setAlignment(HorizontalAlignment.RIGHT);
            dateStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            dateCell.setCellStyle(dateStyle);


            // 3.3 第三行：四个清单标签（居中加粗，带边框）
            Row listRow = sheet.createRow(2);
            listRow.setHeightInPoints(25); // 清单行高
            // 问题清单（列0）
            CellRangeAddress problemMerge = new CellRangeAddress(2, 2, 0, 1);
            sheet.addMergedRegion(problemMerge);
            Cell problemCell = listRow.createCell(0);
            problemCell.setCellValue("问题清单");
            // 任务清单（合并2-4列）
            CellRangeAddress taskMerge = new CellRangeAddress(2, 2, 2, 4);
            sheet.addMergedRegion(taskMerge);
            Cell taskCell = listRow.createCell(2);
            taskCell.setCellValue("任务清单");
            // 责任清单
            Cell responsibilityCell = listRow.createCell(5);
            responsibilityCell.setCellValue("责任清单");
            // 监督清单（合并6-8列）
            CellRangeAddress supervisionMerge = new CellRangeAddress(2, 2, 6, 8);
            sheet.addMergedRegion(supervisionMerge);
            Cell supervisionCell = listRow.createCell(6);
            supervisionCell.setCellValue("监督清单");
            // 清单样式（居中、加粗、带边框）
            CellStyle listStyle = workbook.createCellStyle();
            Font listFont = workbook.createFont();
            listFont.setBold(true);
            listStyle.setFont(listFont);
            listStyle.setAlignment(HorizontalAlignment.CENTER);
            listStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 边框设置（模拟表格线）
            listStyle.setBorderTop(BorderStyle.THIN);
            listStyle.setBorderBottom(BorderStyle.THIN);
            listStyle.setBorderLeft(BorderStyle.THIN);
            listStyle.setBorderRight(BorderStyle.THIN);
            // 应用样式到四个清单单元格
            problemCell.setCellStyle(listStyle);
            taskCell.setCellStyle(listStyle);
            responsibilityCell.setCellStyle(listStyle);
            supervisionCell.setCellStyle(listStyle);

            // 应用样式到四个清单单元格
            // 问题清单（0-1列）
            for (int i = 0; i <= 1; i++) {
                Cell cell = listRow.getCell(i);
                if (cell == null) {
                    cell = listRow.createCell(i);
                }
                cell.setCellStyle(listStyle);
            }

            // 任务清单（2-4列）
            for (int i = 2; i <= 4; i++) {
                Cell cell = listRow.getCell(i);
                if (cell == null) {
                    cell = listRow.createCell(i);
                }
                cell.setCellStyle(listStyle);
            }

            // 责任清单（5-6列）
            for (int i = 5; i <= 6; i++) {
                Cell cell = listRow.getCell(i);
                if (cell == null) {
                    cell = listRow.createCell(i);
                }
                cell.setCellStyle(listStyle);
            }

            // 监督清单（6-8列）
            for (int i = 6; i <= 8; i++) {
                Cell cell = listRow.getCell(i);
                if (cell == null) {
                    cell = listRow.createCell(i);
                }
                cell.setCellStyle(listStyle);
            }

            // 创建表头行
            Row headerRow = sheet.createRow(3);
            headerRow.setHeightInPoints(25); // 设置表头行高


            String[] headers = {"重点领域", "查找本领域存在的突出问题", "落实措施", "完成时间", "落实情况","责任部门(单位)","监督工作开展情况","发现问题及意见建议","监督成效"};

            // 设置列宽（与表头数组对应）
            sheet.setColumnWidth(0, 10 * 256); // 重点领域
            sheet.setColumnWidth(1, 30 * 256); // 查找本领域存在的突出问题
            sheet.setColumnWidth(2, 45 * 256); // 落实措施
            sheet.setColumnWidth(3, 15 * 256); // 完成时间
            sheet.setColumnWidth(4, 20 * 256); // 落实情况
            sheet.setColumnWidth(5, 20 * 256); // 责任部门(单位)
            sheet.setColumnWidth(6, 30 * 256); // 监督工作开展情况
            sheet.setColumnWidth(7, 30 * 256);// 发现问题及意见建议
            sheet.setColumnWidth(8, 30 * 256);// 监督成效
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据行
            int rowNum = 4;
            for (HdSpecialSupervision hdSpecialSupervision: exportList) {
                Row row = sheet.createRow(rowNum++);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String dateStr = sdf.format(hdSpecialSupervision.getCompletionTime());

                setCellValue(row, 0, hdSpecialSupervision.getFocusAreas(), dataStyle);
                setCellValue(row, 1, hdSpecialSupervision.getProblem(), dataStyle);
                setCellValue(row, 2, hdSpecialSupervision.getMeasures(), dataStyle);
                setCellValue(row, 3, dateStr, dataStyle);
                setCellValue(row, 4, hdSpecialSupervision.getImplementationStatus(), dataStyle);
                setCellValue(row, 5, hdSpecialSupervision.getCompanyDepartment(), dataStyle);
                setCellValue(row, 6, hdSpecialSupervision.getWorkProgress(), dataStyle);
                setCellValue(row, 7, hdSpecialSupervision.getIssuesSuggestions(), dataStyle);
                setCellValue(row, 8, hdSpecialSupervision.getMonitoringEffectiveness(), dataStyle);
            }


            // 合并相同列的连续相同单元格
            // 根据表头数组索引合并对应的列

            // 对每个列应用合并逻辑
            mergeSameCells(sheet, 0);
            mergeSameCells(sheet, 1);
            mergeSameCells(sheet, 2);


//            // 智能列宽调整（新增的核心优化）
//            for (int i = 0; i < headers.length; i++) {
//                sheet.autoSizeColumn(i);
//                int currentWidth = sheet.getColumnWidth(i);
//
//                // 动态计算新宽度（中文适配）
//                int newWidth = Math.min(Math.max(
//                        (int)(currentWidth * 1.2) + 512, // 增加20%宽度+额外缓冲
//                        10 * 256                         // 最小宽度10字符
//                ), 100 * 256);                       // 最大宽度限制100字符
//
//                sheet.setColumnWidth(i, newWidth);
//            }

            // 将Excel写入字节数组（关键修改）
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            return baos.toByteArray(); // 返回字节数组
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public int countByFocusAreaName(String areaName) {
        return baseMapper.countByFocusAreaName(areaName);
    }


    // 创建优化的表头样式
    static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        font.setFontName("宋体"); // 使用宋体显示中文
        style.setFont(font);

        // 居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 自动换行
        style.setWrapText(true);

        return style;
    }

    // 创建数据行样式
    static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置自动换行
        style.setWrapText(true);

        // 垂直居中
        style.setVerticalAlignment(VerticalAlignment.TOP); // 顶部对齐更美观

        return style;
    }

    // 设置单元格值并应用样式
    static void setCellValue(Row row, int columnIndex, String value, CellStyle style) {
        if (row == null) return;

        Cell cell = row.createCell(columnIndex);
        cell.setCellValue(value != null ? value : ""); // 防止null值

        // 创建新的样式，确保居中对齐
        CellStyle newStyle = row.getSheet().getWorkbook().createCellStyle();
        if (style != null) {
            newStyle.cloneStyleFrom(style);
        }

        // 设置水平和垂直居中
        newStyle.setAlignment(HorizontalAlignment.CENTER);
        newStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        cell.setCellStyle(newStyle);

        // 特别处理长文本内容，自动调整行高
        if (value != null && value.length() > 0) {
            row.setHeightInPoints(calculateRowHeight(value));
        }
    }

    // 计算行高（根据文本长度）
    private static float calculateRowHeight(String text) {
        int lineCount = (int) Math.ceil(text.length() / 20.0); // 每80字符为一行
        return Math.max(100, 15 * lineCount); // 最小行高50，每行增加15
    }

    // 合并相同列的连续相同单元格
    static void mergeSameCells(Sheet sheet, int columnIndex) {
        int startRow = 4; // 数据从第2行开始（索引1）
        int lastRow = sheet.getLastRowNum();

        if (lastRow <= startRow) return;

        for (int i = startRow + 1; i <= lastRow; i++) {
            Row currentRow = sheet.getRow(i);
            Row previousRow = sheet.getRow(i - 1);

            if (currentRow == null || previousRow == null) continue;

            Cell currentCell = currentRow.getCell(columnIndex);
            Cell previousCell = previousRow.getCell(columnIndex);

            String currentValue = getCellValueAsString(currentCell);
            String previousValue = getCellValueAsString(previousCell);

            if (!currentValue.equals(previousValue)) {
                if (i - 1 > startRow) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow, i - 1, columnIndex, columnIndex));

                    // 合并后居中显示
                    centerMergedCells(sheet, startRow, i - 1, columnIndex);
                }
                startRow = i;
            } else if (i == lastRow) {
                sheet.addMergedRegion(new CellRangeAddress(startRow, i, columnIndex, columnIndex));

                // 合并后居中显示
                centerMergedCells(sheet, startRow, i, columnIndex);
            }
        }
    }

    // 获取单元格值
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        return cell.getStringCellValue();
    }

    // 合并后单元格垂直居中
    private static void centerMergedCells(Sheet sheet, int firstRow, int lastRow, int column) {
        CellStyle originalStyle = sheet.getRow(firstRow).getCell(column).getCellStyle();
        CellStyle style = sheet.getWorkbook().createCellStyle();
        style.cloneStyleFrom(originalStyle);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        for (int i = firstRow; i <= lastRow; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                Cell cell = row.getCell(column);
                if (cell != null) {
                    cell.setCellStyle(style);
                }
            }
        }
    }
}
